package com.gm.wholesale.module.order.ui

import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.text.TextUtils
import android.util.ArrayMap
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ListView
import android.widget.TextView
import com.gm.commonlib.base.baseAdapter.CommonAdapter
import com.gm.commonlib.base.baseAdapter.ViewHolder
import com.gm.commonlib.base.baseView.IBaseView
import com.gm.commonlib.base.baseui.baseFragment.BaseFragment
import com.gm.commonlib.module.evenbus.EventMessage
import com.gm.commonlib.util.numberUtils.NumberUtils
import com.gm.commonlib.util.permission.PermissionUtil
import com.gm.commonlib.util.permission.interfaces.IPermissionCallback
import com.gm.commonlib.util.stringUtils.StringUtils
import com.gm.commonlib.util.timeUtils.DateTimeUtils
import com.gm.commonlib.util.viewUtils.RepeatClickUtils
import com.gm.commonlib.util.viewUtils.ViewUtil
import com.gm.commonlib.views.BadgeView
import com.gm.commonlib.views.dialog.DialogUtil
import com.gm.commonlib.views.dialog.InputDialog
import com.gm.commonlib.views.popupwindow.Popupwindow
import com.gm.commonlib.views.popupwindow.Popupwindow2
import com.gm.commonlib.views.toast.ToastUtil
import com.gm.wholesale.GMApplication
import com.gm.wholesale.R
import com.gm.wholesale.cacheData.CacheData
import com.gm.wholesale.databinding.FragmentOrderBinding
import com.gm.wholesale.db.order.DBOrderUtil
import com.gm.wholesale.db.order.bean.DBOrderBean
import com.gm.wholesale.db.order.bean.DBOrderContentBean
import com.gm.wholesale.module.config.ConfigData
import com.gm.wholesale.module.custom.ChoiceCustomData
import com.gm.wholesale.module.custom.bean.CustomBean
import com.gm.wholesale.module.evenbus.EvenBusUtil
import com.gm.wholesale.module.evenbus.EventBusType
import com.gm.wholesale.module.good.bean.GoodBean
import com.gm.wholesale.module.main.ui.MainActivity
import com.gm.wholesale.module.order.bean.OrderDetailBean
import com.gm.wholesale.module.order.presenter.CreateOrderPresenter
import com.gm.wholesale.module.order.presenter.MainOrderFgPresenter
import com.gm.wholesale.module.order.presenter.MainOrderFgPresenter.OnSearchGoodFinishListener
import com.gm.wholesale.module.order.view.ChoiceGoodTagView
import com.gm.wholesale.util.AppUtil
import com.gm.wholesale.util.CloneUtil

class MainOrderFragment : BaseFragment(), View.OnClickListener {
    private var mMainActivity: MainActivity? = null
    private val mGoodBeans: MutableList<GoodBean>? = ArrayList()
    private var mAdapter: CommonAdapter<*>? = null
    private var mainOrderView: FragmentOrderBinding? = null;
    private var mBadgeView: BadgeView? = null
    private var orderId: Long = 0
    private var orderVersion: Long = 0
    override fun onCreateContentBody(parent: ViewGroup) {
        super.onCreateContentBody(parent)
        //这个fragment 默认在 xml 配置了。默认就会创建，这里加个处理
        if (!ConfigData.getConfigData().hasCreateOrderPermission()) { //没有开单权限，进入订单管理界面
            return
        }
        mainOrderView = FragmentOrderBinding.inflate(LayoutInflater.from(context), parent, true);
        initView(mainOrderView!!);
        showSaveOrderSize()
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mMainActivity = context as MainActivity
    }

    override fun onReceiveEvent(event: EventMessage<*>?) {
        super.onReceiveEvent(event)
        if (event == null) return
        //todo 显示默认散客信息
        val evenType = event.code
        if (evenType == EventBusType.SHOW_DEFAULT_CUSTORM.type) {
            showCustomView(event.data as CustomBean)
        } else if (evenType == EventBusType.CLERAN_ORDER.type) {
            clearData()
        }
        if (event.code == EventBusType.UPDATE_ORDER.type) {
            val orderDetailBean = event.data as OrderDetailBean
            val customerInfo = orderDetailBean.customerInfo
            val customBean = CustomBean()
            customBean.name = customerInfo.customerName
            customBean.id = customerInfo.customerId.toLong()
            ChoiceCustomData.newInstance().customBean = customBean
            val goodBeans: MutableList<GoodBean> = ArrayList()
            val orderDetails = orderDetailBean.orderDetails
            if (orderDetails != null) {
                for (orderDetailsDTO in orderDetails) {
                    val goodBean = GoodBean()
                    goodBean.setId(orderDetailsDTO.skuId)
                    goodBean.setName(orderDetailsDTO.skuName)
                    goodBean.goodNum = orderDetailsDTO.quantity.toDouble()
                    goodBean.price = orderDetailsDTO.unitPrice.toDouble()
                    goodBean.unitName = orderDetailsDTO.orderingUnitName
                    goodBean.tempId = AppUtil.getUUid()
                    goodBean.orderLineId = orderDetailsDTO.orderLineId
                    goodBean.setUnits(orderDetailsDTO.units)
                    var totalPrice = 0.0
                    totalPrice = if (goodBean.goodNum < 0 || goodBean.price < 0) {
                        0.0
                    } else {
                        NumberUtils.mul(goodBean.goodNum, goodBean.price)
                    }
                    goodBean.totalPrice = totalPrice
                    goodBeans.add(goodBean)
                }
            }
            val orderInfoDTO = orderDetailBean.orderInfo
            showUpdateView(goodBeans, orderInfoDTO.orderId, orderInfoDTO.version)
            if (mMainActivity != null) {
                mMainActivity!!.showMainUI()
            }
        }
    }

    //todo 获取展示 挂单数量
    private fun showSaveOrderSize() {
        if (mMainActivity != null) {
            val orderSize = DBOrderUtil.getOrderSize(mMainActivity!!.gMApplication.databaseHelper)
            remindMsg(mBadgeView, orderSize)
        }
    }

    private fun showCustomView(customBean: CustomBean?) {
        if (customBean != null) {
            mainOrderView?.choiceUserTv?.text = customBean.name
        }
    }

    private fun initView(view: FragmentOrderBinding) {
        mBadgeView = BadgeView(context, view.showNtTv)
        view.cancelOrderTv?.setOnClickListener(this)
        view.arrearsTv?.setOnClickListener(this)
        view.choiceUserTv?.setOnClickListener(this)
        view.saveOrderToLocalTv?.setOnClickListener(this)
        view.showSaveOrdersTv?.setOnClickListener(this)
        view.submitOrderTv?.setOnClickListener(this)
        view.voiceImage?.setOnClickListener(this)
        handleVoiceImage()
    }

    //todo 有语音录入权限 才显示按钮
    private fun handleVoiceImage() {
        mainOrderView?.voiceImage?.visibility = View.GONE
        if (ConfigData.getConfigData() != null) {
            if (ConfigData.getConfigData().hasVoicePermission()) {
                mainOrderView?.voiceImage?.visibility = View.VISIBLE
            }
        }
    }

    private fun remindMsg(badgeView: BadgeView?, size: Int) {
        badgeView!!.badgePosition =
            BadgeView.POSITION_TOP_RIGHT // 显示的位置.右上角,BadgeView.POSITION_BOTTOM_LEFT,下左，还有其他几个属性
        badgeView.setTextColor(Color.WHITE) // 文本颜色
        badgeView.badgeBackgroundColor = Color.RED // 提醒信息的背景颜色，自己设置
        badgeView.textSize = 12f // 文本大小
        badgeView.setBadgeMargin(0, 0)
        badgeView.show() // 只有显示
        if (size > 99) {
            badgeView.text = "99+" // 需要显示的提醒类容
        } else {
            badgeView.text = size.toString() + "" // 需要显示的提醒类容
        }
        if (size <= 0) {
            badgeView.hide()
        }
    }

    private fun checkAutoPermission() {
        PermissionUtil.applyAudioPermission(activity, object : IPermissionCallback() {
            override fun onPermissionResult(result: Boolean, dataSet: Set<String>) {
                if (result) {
                    mMainActivity!!.startVoice()
                } else {
                    ToastUtil.showToast("请打开录音权限")
                }
            }
        })
    }

    override fun onClick(view: View) {
        if (RepeatClickUtils.check()) {
            return
        }
        val viewId = view.id
        if (viewId == R.id.voiceImage) {
            checkAutoPermission()
            return
        }
        if (viewId == R.id.choiceUserTv) {
            mMainActivity!!.showChoiceCustom()
            return
        }
        if (viewId == R.id.cancelOrderTv) {
            if (mGoodBeans.isNullOrEmpty()) {
                return
            }
            DialogUtil.show(
                activity,
                "是否整单取消?"
            ) { _: DialogInterface?, _: Int -> clearData() }
            return
        }
        if (viewId == R.id.saveOrderToLocalTv) {
            saveCurrentOrderToDB()
        }
        if (viewId == R.id.showSaveOrdersTv) {
            val application = requireActivity().application as GMApplication
            val dbOrderBeans = DBOrderUtil.getDBOrderBean(application.databaseHelper)
            if (dbOrderBeans == null || dbOrderBeans.isEmpty()) {
                return
            }
            val popListView =
                LayoutInflater.from(context).inflate(R.layout.view_pop_order_size, null)
            val listView = popListView.findViewById<ListView>(com.gm.commonlib.R.id.listView)
            val defaultName = "挂单"
            listView.adapter = object :
                CommonAdapter<DBOrderBean?>(context, dbOrderBeans, R.layout.list_pop_order_item) {
                override fun convert(view: ViewHolder?, data: DBOrderBean?) {
                    val pos = view?.position?.plus(1)
                    //兼容老数据做一个判断。没有客户名字显示挂单xx，有客户名字显示客户名字（开始没保存客户名字）
                    //后面需求要求 新加
                    if (TextUtils.isEmpty(data?.other1)) {
                        view?.setText(R.id.nameTv, defaultName + pos)
                    } else {
                        view?.setText(R.id.nameTv, data?.other1)
                    }
                    view?.setText(
                        R.id.createTimeTv,
                        DateTimeUtils.formatDateTime(data!!.time, DateTimeUtils.HMD)
                    )
                    view?.convertView?.setOnClickListener { _: View? ->
                        if (!mGoodBeans.isNullOrEmpty()) {
                            DialogUtil.show(
                                activity, "正在开单，取单后当前订单将挂起，是否取单？"
                            ) { _: DialogInterface?, _: Int ->
                                saveCurrentOrderToDB()
                                if (data != null) {
                                    getOrderByDB(data)
                                }
                                Popupwindow.hiddenPop()
                            }
                        } else {
                            if (data != null) {
                                getOrderByDB(data)
                            }

                        }
                    }
                }
            }
            Popupwindow2.showPopView(activity, mainOrderView?.showSaveOrdersTv, popListView)
        }
        if (viewId == R.id.submitOrderTv) {
            val errorMsg = checkOrderData()
            if (!StringUtils.isEmpty(errorMsg)) {
                ToastUtil.showToast(errorMsg)
                return
            }
            //修改订单
            if (orderId > 0) {
                updateOrder()
            } else { //创建新订单
                subMitOrder()
            }
            return
        }
    }

    //todo 提交订单
    private fun subMitOrder() {
        CreateOrderPresenter.subMitOrder(
            context, mGoodBeans
        ) { EvenBusUtil.clearnHomeOrder() }
    }

    private fun updateOrder() {
        CreateOrderPresenter.updateOrder(
            context, orderId, orderVersion, mGoodBeans
        ) { EvenBusUtil.clearnHomeOrder() }
    }

    private fun checkOrderData(): String {
        return if (mGoodBeans.isNullOrEmpty()) {
            "请先创建订单"
        } else ""
    }

    // todo 保存当前录单到本地数据库
    private fun saveCurrentOrderToDB() {
        if (mGoodBeans!!.isEmpty()) {
            return
        }
        val application = requireActivity().application as GMApplication
        val orderContentBeans: MutableList<DBOrderContentBean> = ArrayList()
        for (goodBean in mGoodBeans) {
            orderContentBeans.add(goodBean.toDBOrderBean())
        }
        DBOrderUtil.saveOrder(application.databaseHelper, orderContentBeans)
        showSaveOrderSize()
        clearData()
    }

    private fun getOrderByDB(data: DBOrderBean) {
        Popupwindow2.hiddenPop()
        val databaseHelper = mMainActivity!!.gMApplication.databaseHelper
        val orderContentBeans = DBOrderUtil.getDBOrderDetailByOrderId(databaseHelper, data.orderId)
            ?: return
        mGoodBeans!!.clear()
        for (orderContentBean in orderContentBeans) {
            mGoodBeans.add(orderContentBean.toGoodBean())
        }
        if (orderContentBeans != null && !orderContentBeans.isEmpty()) {
            updateCustom(orderContentBeans[0])
        }
        updateView()
        DBOrderUtil.deleteOrder(databaseHelper, data.id.toLong())
        showSaveOrderSize()
    }

    private fun updateCustom(orderContentBean: DBOrderContentBean?) {
        if (orderContentBean != null) {
            val customBean = orderContentBean.customBean
            if (customBean != null) {
                ChoiceCustomData.newInstance().customBean = customBean
                mMainActivity!!.updateCustom(customBean)
            }
        }
    }

    private fun clearData() {
        orderId = 0
        orderVersion = 0
        if (mAdapter != null && mGoodBeans != null) {
            mGoodBeans.clear()
            mAdapter!!.notifyDataSetChanged()
        }
        if (ChoiceCustomData.mSanKeCustomBean != null) {
            showCustomView(ChoiceCustomData.mSanKeCustomBean)
            ChoiceCustomData.newInstance().customBean = ChoiceCustomData.mSanKeCustomBean
        } else {
            mMainActivity!!.getDefaultCustom()
        }
        resetTotalPrice()
    }

    private fun resetTotalPrice() {
        mainOrderView?.totalPriceTv?.text = "￥0.00"

    }


    private fun showUpdateView(goodBeans: List<GoodBean>?, orderId: Long, orderVersion: Long) {
        this.orderId = orderId
        this.orderVersion = orderVersion
        mGoodBeans!!.clear()
        mGoodBeans.addAll(goodBeans!!)
        // todo 更新客户信息
        showCustomView(ChoiceCustomData.newInstance().customBean)
        updateView()
    }

    fun addGoodBean(goodBean: GoodBean?) {
        goodBean?.let {
            var totalPrice = NumberUtils.mul(goodBean.goodNum, goodBean.price)
            if (totalPrice < 0) {
                totalPrice = 0.0
            }
            goodBean.totalPrice = totalPrice
            if (TextUtils.isEmpty(goodBean.tempId)) {
                goodBean.tempId = AppUtil.getUUid()
                mGoodBeans!!.add(goodBean)
            } else {
                var mIsExit = false
                for (goodBean1 in mGoodBeans!!) {
                    if (goodBean1.tempId == goodBean.tempId) {
                        mIsExit = true
                        goodBean1.isIsVoiceCreate = goodBean.isIsVoiceCreate
                        goodBean1.goodNum = goodBean.goodNum
                        goodBean1.isTemporaryGood = goodBean.isTemporaryGood
                        goodBean1.setId(goodBean.getId())
                        goodBean1.unitName = goodBean.unitName
                        goodBean1.price = goodBean.price
                        goodBean1.unitId = goodBean.unitId
                        goodBean1.totalPrice = totalPrice
                        goodBean1.setName(goodBean.getName())
                        goodBean1.searchGoods = goodBean.searchGoods
                        goodBean1.setAddWeightBeans(goodBean.getAddWeightBeans())
                        break
                    }
                }
                if (!mIsExit) {
                    goodBean.tempId = AppUtil.getUUid()
                    mGoodBeans.add(goodBean)
                }
            }
            updateView()

        }

    }

    private fun showTotalPrice() {
        var total = 0.0
        for (goodBean in mGoodBeans!!) {
            if (goodBean.price >= 0) {
                total = NumberUtils.addDouble(total, goodBean.totalPrice)
            }
        }
        if (total <= 0) {
            resetTotalPrice()
        } else {
            setTotalPriceTv(total)
        }
    }

    private fun setTotalPriceTv(data: Double) {
        mainOrderView?.totalPriceTv?.text = "￥" + NumberUtils.getMoneyString(data)
    }

    fun updateView() {
        showTotalPrice()
        if (mAdapter != null) {
            mAdapter!!.notifyDataSetChanged()
            return
        }
        mAdapter =
            object : CommonAdapter<GoodBean?>(
                context,
                mGoodBeans as List<GoodBean?>?,
                R.layout.list_order_item
            ) {
                override fun convert(view: ViewHolder?, good: GoodBean?) {
                    val goodNameTv = view?.getView<TextView>(R.id.goodNameTv)
                    if (good?.getId()!! <= 0) {
                        ViewUtil.setCompoundDrawables(
                            activity,
                            goodNameTv,
                            ViewUtil.POS_LEFT,
                            R.drawable.new_good
                        )
                    } else {
                        ViewUtil.cleanDrawable(goodNameTv)
                    }
                    view?.let {
                        view.setText(R.id.goodNameTv, good.getName())
                        view.setText(R.id.goodNumTv, NumberUtils.getMoneyString(good.goodNum))
                        view.setText(R.id.goodUnitTv, good.unitName)
                        view.setText(R.id.goodPriceTv, NumberUtils.getMoneyString(good.price))
                        view.setText(R.id.totalPriceTv, NumberUtils.getMoneyString(good.totalPrice))
                        view.getView<View>(R.id.deleteOrderImg).setOnClickListener { _: View? ->
                            DialogUtil.show(
                                activity,
                                "是否删除该商品?"
                            ) { _: DialogInterface?, _: Int ->
                                mGoodBeans!!.remove(good)
                                //todo 如果删除完了，则订单id置空。不然添加商品 会走修改订单逻辑
                                if (mGoodBeans.isEmpty()) {
                                    orderId = 0
                                }
                                showTotalPrice()
                                notifyDataSetChanged()
                            }
                        }
                        // todo 新商品才能修改
                        if (good.getId() <= 0) {
                            view.getView<View>(R.id.goodNameTv).setOnClickListener {
                                if (good.getId() <= 0) { //todo 新商品才能修改
                                    updateGoodName(good)
                                }
                            }
                        }
                        view.convertView.setOnClickListener {
                            good.isIsUpdateView = true
                            var newGood = CloneUtil.clone(good)
                            if (newGood == null) {
                                newGood = good
                            }
                            //商品id小于0 说明是新商品（则是语音录入创建的商品）
                            if (good.getId() <= 0) {
                                mMainActivity!!.updateGoodForVoiceView(newGood)
                            } else {
                                mMainActivity!!.showCreateOrderView(newGood)
                            }
                        }

                    }
                }
            }

        mainOrderView?.orderListView?.adapter = mAdapter
    }

    private fun updateGood(goodBean: GoodBean, newGood: GoodBean) {
        goodBean.unitName = newGood.unitName
        goodBean.setName(newGood.getName())
        if (CacheData.getIsAutoInputPrice()) {
            goodBean.price = newGood.priceByJin
        }
        goodBean.setId(newGood.getId())
        addGoodBean(goodBean)
    }

    //修改商品名称
    private fun updateGoodName(goodBean: GoodBean?) {
        if (goodBean != null) {
            val inputDialog1 = DialogUtil.showInputDialog(
                content,
                "修改商品名称",
                goodBean.getName()
            ) { inputData: String?, inputDialog: InputDialog ->
                if (TextUtils.isEmpty(inputData)) {
                    ToastUtil.showToast("请输入商品名称")
                    return@showInputDialog
                }
                inputDialog.dismiss()
                val queryData = ArrayMap<String, Any?>()
                queryData["name"] = inputData
                MainOrderFgPresenter.searchGoodByName(
                    activity as IBaseView<*>?,
                    queryData,
                    OnSearchGoodFinishListener { goodBeans ->
                        if (goodBeans != null && goodBeans.isNotEmpty()) {
                            updateGood(goodBean, goodBeans[0])
                        } else {
                            //新商品
                            goodBean.setName(inputData)
                            goodBean.setId(0)
                            mAdapter!!.notifyDataSetChanged()
                        }
                    })
            }
            val choiceGoodTagView = ChoiceGoodTagView(activity)
            MainOrderFgPresenter.searchGoodByKey(
                null,
                goodBean.getName(),
                OnSearchGoodFinishListener { goodBeans ->
                    if (goodBeans != null && goodBeans.isNotEmpty()) {
                        if (goodBeans.size == 1 && goodBean.getName() == goodBeans[0].getName() && goodBean.unitName == goodBeans[0].unitName) {
                            return@OnSearchGoodFinishListener
                        }
                        val newGoods: MutableList<GoodBean> = ArrayList()
                        for (searchGood in goodBeans) {
                            if (goodBean.getName() != searchGood.getName()
                                || goodBean.unitName != searchGood.unitName
                            ) {
                                newGoods.add(searchGood)
                            }
                        }
                        if (newGoods.isEmpty()) {
                            return@OnSearchGoodFinishListener
                        }
                        choiceGoodTagView.showView(newGoods) { newGood ->
                            inputDialog1.dismiss()
                            updateGood(goodBean, newGood)
                        }
                        inputDialog1.setContentView(choiceGoodTagView)
                    }
                })
        }
    }
}